package com.scale.service.voice.service.impl;

import com.example.voice.entity.VoiceProcessingTasks;
import com.scale.service.voice.mapper.VoiceProcessingTasksMapper;
import com.example.voice.vo.TaskProgressMessage;
import com.scale.service.voice.service.TaskProgressService;
import com.scale.service.voice.service.VoiceTaskWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 任务进度服务实现类
 * @author crp
 * @since 2025-01-26
 */
@Service
public class TaskProgressServiceImpl implements TaskProgressService {
    
    @Autowired
    private VoiceProcessingTasksMapper voiceTaskMapper;
    
    @Autowired
    private VoiceTaskWebSocketHandler webSocketHandler;
    
    @Override
    public void updateProgress(String taskId, String currentStep, Integer progress, String message) {
        System.out.println("更新任务进度: taskId=" + taskId + ", step=" + currentStep + ", progress=" + progress);
        
        // 更新数据库中的任务进度
        VoiceProcessingTasks task = voiceTaskMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VoiceProcessingTasks>()
                .eq("task_id", taskId)
        );
        
        if (task != null) {
            task.setCurrentStep(currentStep);
            task.setProgress(progress);
            task.setUpdatedAt(LocalDateTime.now());
            voiceTaskMapper.updateById(task);
            System.out.println("数据库进度更新成功: " + taskId);
        } else {
            System.out.println("任务不存在，无法更新进度: " + taskId);
        }
        
        // 发送WebSocket消息
        TaskProgressMessage progressMessage = new TaskProgressMessage();
        progressMessage.setType("PROGRESS_UPDATE");
        progressMessage.setTaskId(taskId);
        
        TaskProgressMessage.TaskProgressData data = new TaskProgressMessage.TaskProgressData();
        data.setStatus("PROCESSING");
        data.setProgress(progress);
        data.setCurrentStep(currentStep);
        data.setMessage(message);
        data.setTimestamp(LocalDateTime.now());
        
        if (task != null) {
            data.setRecognizedText(task.getRecognizedText());
            data.setAiReply(task.getAiReply());
            data.setVoiceUrl(task.getVoiceUrl());
            data.setUserVoiceUrl(task.getUserVoiceUrl());
            data.setConversationId(task.getConversationId());
        }
        
        progressMessage.setData(data);
        
        if (task != null) {
            String userId = String.valueOf(task.getUserId());
            System.out.println("发送WebSocket进度更新: taskId=" + taskId + ", userId=" + userId);
            System.out.println("用户WebSocket会话状态: " + webSocketHandler.getUserSessionInfo(userId));
            webSocketHandler.sendProgressUpdate(taskId, userId, progressMessage);
        } else {
            System.err.println("❌ 任务不存在，无法发送WebSocket进度更新: " + taskId);
        }
    }
    
    @Override
    public void sendProgressUpdate(String taskId, TaskProgressMessage message) {
        // 🔧 获取任务信息以获取用户ID
        VoiceProcessingTasks task = voiceTaskMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VoiceProcessingTasks>()
                .eq("task_id", taskId)
        );
        
        if (task != null) {
            String userId = String.valueOf(task.getUserId());
            webSocketHandler.sendProgressUpdate(taskId, userId, message);
        } else {
            System.err.println("❌ 任务不存在，无法发送WebSocket消息: " + taskId);
        }
    }
    
    @Override
    public void sendTaskCompleted(String taskId, String recognizedText, String aiReply, String voiceUrl) {
        // 获取任务信息以包含完整数据
        VoiceProcessingTasks task = voiceTaskMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VoiceProcessingTasks>()
                .eq("task_id", taskId)
        );
        
        TaskProgressMessage message = new TaskProgressMessage();
        message.setType("TASK_COMPLETED");
        message.setTaskId(taskId);
        
        TaskProgressMessage.TaskProgressData data = new TaskProgressMessage.TaskProgressData();
        data.setStatus("COMPLETED");
        data.setProgress(100);
        data.setCurrentStep("STORAGE");
        data.setMessage("处理完成！");
        data.setRecognizedText(recognizedText);
        data.setAiReply(aiReply);
        data.setVoiceUrl(voiceUrl);
        data.setTimestamp(LocalDateTime.now());
        
        // 包含完整的任务信息
        if (task != null) {
            data.setUserVoiceUrl(task.getUserVoiceUrl());
            data.setConversationId(task.getConversationId());
        }
        
        message.setData(data);
        
        if (task != null) {
            String userId = String.valueOf(task.getUserId());
            System.out.println("发送任务完成消息: taskId=" + taskId + ", userId=" + userId);
            System.out.println("用户WebSocket会话状态: " + webSocketHandler.getUserSessionInfo(userId));
            webSocketHandler.sendProgressUpdate(taskId, userId, message);
        } else {
            System.err.println("❌ 任务不存在，无法发送任务完成消息: " + taskId);
        }
    }
    
    @Override
    public void sendTaskFailed(String taskId, String errorCode, String errorMessage) {
        TaskProgressMessage message = new TaskProgressMessage();
        message.setType("TASK_FAILED");
        message.setTaskId(taskId);
        
        TaskProgressMessage.TaskProgressData data = new TaskProgressMessage.TaskProgressData();
        data.setStatus("FAILED");
        data.setErrorCode(errorCode);
        data.setErrorMessage(errorMessage);
        data.setTimestamp(LocalDateTime.now());
        
        message.setData(data);
        
        // 🔧 获取任务信息以获取用户ID
        VoiceProcessingTasks task = voiceTaskMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<VoiceProcessingTasks>()
                .eq("task_id", taskId)
        );
        
        if (task != null) {
            String userId = String.valueOf(task.getUserId());
            System.out.println("发送任务失败消息: taskId=" + taskId + ", userId=" + userId);
            System.out.println("用户WebSocket会话状态: " + webSocketHandler.getUserSessionInfo(userId));
            webSocketHandler.sendProgressUpdate(taskId, userId, message);
        } else {
            System.err.println("❌ 任务不存在，无法发送任务失败消息: " + taskId);
        }
    }
}
